<template>
  <div class="ball-container">
    <div v-for="(ball, index) in balls" :key="index">
      <transition
        @before-enter="beforeDrop"
        @enter="dropping"
        @after-enter="afterDrop"
      >
        <div class="ball" v-show="ball.show">
          <div class="inner inner-hook"></div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
const BALL_LENG = 10
const innerClsHook = 'inner-hook'



function createBalls() {
  const balls = []
  for (let i = 0; i < BALL_LENG; i++) {
    balls.push({ show: false })
  }
  return balls
}

export default {
  name: 'ballsAnimation',
  props: {},
  data() {
    return {
      balls: createBalls()
    }
  },
  created() {
    this.dropBalls = []
  },
  methods: {
    dropBall(el) {
      for (let i = 0; i < this.balls.length; i++) {
        let ball = this.balls[i]
        if (!ball.show) {
          ball.show = true
          ball.el = el
          this.dropBalls.push(ball)
          return
        }
      }
    },
    beforeDrop(el) {
      const ball = this.dropBalls[this.dropBalls.length - 1]
      const rect = ball.el.getBoundingClientRect()
      const x = rect.left - 32
      const y = -(window.innerHeight - rect.top - 22)

      el.style.display = ''
      el.style.transform = el.style.webkitTransform = `translate3d(0,${y}px,0)`
      const inner = el.getElementsByClassName(innerClsHook)[0]
      inner.style.transform = inner.style.webkitTransform = `translate3d(${x}px,0,0)`
    },
    dropping(el, done) {
      this._reflow = document.body.offsetHeight
      el.style.transform = el.style.webkitTransform = 'translate3d(0,0,0)'
      const inner = el.getElementsByClassName(innerClsHook)[0]
      inner.style.transform = inner.style.webkitTransform = 'translate3d(0,0,0)'
      el.addEventListener('transitionend', done)
    },
    afterDrop(el) {
      const ball = this.dropBalls.shift()
      if (ball) {
        ball.show = false
        el.style.display = 'none'
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.ball-container {
  .ball {
    position: fixed;
    left: 32px;
    bottom: 22px;
    width: 16px;
    height: 16px;
    z-index: 200;
    transition: all 0.4s cubic-bezier(0.49, -0.29, 0.75, 0.41);

    .inner {
      display: inline-block;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: #00a0dc;
      transition: all 0.4s linear;
    }
  }
}
</style>
